//
//  SFBasicPerformer.m
//  Sofia
//
//  Created by Anton Chebotaev on 26/11/08.
//  Copyright 2008 IFMO. All rights reserved.
//

#import "SFBasicPerformer.h"
#import "iTunes.h"
#import "SFMusicFormatToken.h"


@implementation SFBasicPerformer
- (id)init
{
	if (self = [super init]) {
		// do all stuff here;
	}
	return self;
}

+ (SFBasicPerformer *)sharedBasicPerformer
{
	return [[[SFBasicPerformer alloc] init] autorelease];
}

- (void)dealloc
{
    [super dealloc];
}


- (NSString *)getFormatedMusicString
{
    NSData *musicFormatAsData = [[NSUserDefaults standardUserDefaults] objectForKey:SFAMusicFormat];
	NSArray *musicFormatArray = [NSKeyedUnarchiver unarchiveObjectWithData:musicFormatAsData];
	NSString *silenceFormat = [[NSUserDefaults standardUserDefaults] objectForKey:SFATextValue];

    iTunesApplication *iTunes = [[SBApplication alloc] initWithBundleIdentifier:@"com.apple.iTunes"];
	NSMutableString *result = [[NSMutableString alloc] init];
	
	if((![iTunes isRunning]) || ([iTunes playerState] != iTunesEPlSPlaying))
	{
		[result appendString:silenceFormat];
	}
	else
	{
		iTunesTrack *savedTrack = [iTunes currentTrack];
		
		NSEnumerator *formatEnumerator = [musicFormatArray objectEnumerator];
		for (SFMusicFormatToken *element in formatEnumerator) {
			if([element class] != [SFMusicFormatToken class])
			{
				NSLog(@"SFMusicViewController: There is not a SFMusicFormatToken object in musicFormatArray");
				continue;
			}
			
			if ([[element content] isEqualToString:SFATitleToken])
			{
				[result appendString:[savedTrack name]];
			}
			else if ([[element content] isEqualToString:SFAAlbumToken])
			{
				[result appendString:[savedTrack album]];
			}
			else if ([[element content] isEqualToString:SFAArtistToken])
			{
				[result appendString:[savedTrack artist]];
			}
			else if ([[element content] isEqualToString:SFAGenreToken])
			{
				[result appendString:[savedTrack genre]];
			}
			else if ([[element content] isEqualToString:SFARatingToken])
			{
				int stars = [savedTrack rating] / 20;
				for(int i = 0; i < stars; i++)
					[result appendString:@"★"];				
			}
			else
			{
				[result appendString:[element presentation]];
			}
		}// for (SFMusicFormatToken *element in formatEnumerator)
	} // eod of if(![iTunes isRunning])
	
	[iTunes release];
	return [result autorelease];
}

@end
